﻿using DDD.Core.CQRS;
using DDD.Core.DependencyInjection;
using DDD.Core.Vaildate;
using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Modularity;

namespace DDD.Core
{
    public sealed class CoreModule: AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddIOC();
            AddCommandAndQuery(context.Services);
            AddValidator(context.Services);
        }

        /// <summary>
        /// 添加命令与查询
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private void AddCommandAndQuery(IServiceCollection services)
        {
            var option = IOC.GetOption<CQRSOption>();

            services.AddMediatR(c =>
            {
                c.AddOpenBehavior(typeof(VaildateBehavior<,>));
                if (option.BehaviorTypes != null && option.BehaviorTypes.Length != 0)
                {
                    foreach (var behaviorType in option.BehaviorTypes)
                        c.AddOpenBehavior(behaviorType);
                }

                c.RegisterServicesFromAssemblies(option.Assemblies);
            });
        }

        /// <summary>
        /// 添加验证器
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private void AddValidator(IServiceCollection services)
        {
            var option = IOC.GetOption<ValidateOption>();

            services.AddValidatorsFromAssembly(option.Assembly, option.Lifetime);
        }
    }
}
